#define _CRT_SECURE_NO_WARNINGS
#include "SeqList.h"

#define Init 4
void SLInit(SeqList* psl) {
	psl->a = (SLDataType*)malloc(sizeof(SLDataType) * Init);
	if (psl->a == NULL) {
		perror("malloc fail\n");
		return;
	}
	psl->capacity = Init;
	psl->size = 0;
}
void SLDestroy(SeqList* psl) {
	free(psl->a);
	psl->a = NULL;
	psl->capacity = 0;
	psl->size = 0;

}
void SLPrint(SeqList* psl) {
	for (int i = 0; i < psl->size; i++) {
		printf("%d ", psl->a[i]);
	}
	printf("\n");
}
void SLCheckCapacity(SeqList* psl) {
	if (psl->size == psl->capacity) {
		SLDataType* tmp = (SLDataType*)realloc(psl->a, sizeof(SLDataType) * psl->capacity*2);
		if (tmp == NULL) {
			perror("relloc fail\n");
			return;
		}
		psl->a = tmp;
		psl->capacity *= 2;
	}
	
}
void SLPushBack(SeqList* psl, SLDataType x) {
	/*SLCheckCapacity(psl);
	psl->a[psl->size++] = x;*/
	SLInsert(psl, psl->size, x);
}
void SLPushFront(SeqList* psl, SLDataType x) {
	/*SLCheckCapacity(psl);
	int end = psl->size - 1;
	while (end >= 0) {
		psl->a[end + 1] = psl->a[end];
		end--;
	}
	psl->a[0] = x;
	psl->size++;*/
	SLInsert(psl, 0,  x);
}
void SLPopBack(SeqList* psl) {
	/*assert(psl->size > 0);
	psl->size--;*/
	SLErase( psl, psl->size-1);
}
void SLPopFront(SeqList* psl) {
	/*assert(psl->size > 0);
	int start = 0;
	while (start < psl->size-1) {
		psl->a[start] = psl->a[start + 1];
		start++;
	}
	psl->size--;*/
	SLErase(psl, 0);
}

void SLInsert(SeqList* psl, int pos, SLDataType x) {
	SLCheckCapacity(psl);
	assert(pos >= 0 && pos <= psl->size);
	int end = psl->size - 1;
	while (end >= pos) {
		psl->a[end + 1] = psl->a[end];
		end--;
	}
	psl->a[pos] = x;
	psl->size++;
}

void SLErase(SeqList* psl, int pos) {
	assert(pos >= 0 && pos < psl->size);
	int start = pos+1;
	while (start < psl->size) {
		psl->a[start - 1] = psl->a[start];
		start++;
	}
	psl->size--;

}
int SLFind(SeqList* psl, SLDataType x) {
	for (int i = 0; i < psl->size; i++)
	{
		if (psl->a[i] == x) {
			return i;
		}
	}
	return -1;
}
void SLModify(SeqList* psl, int pos, SLDataType x) {
	assert(pos >= 0 && pos < psl->size);
	psl->a[pos] = x;

}